import os
from config import Config

class AI:
    def __init__(self, model):
        self.api_key = Config.API_KEY
        self.api_url = Config.API_URL
        self.model = model
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def _make_api_request(self, messages):
        """发送API请求的通用方法"""
        import requests
        
        payload = {
            "model": self.model,
            "messages": messages,
            "temperature": 0.7
        }
        
        try:
            response = requests.post(self.api_url, headers=self.headers, json=payload)
            response.raise_for_status()
            return response.json()['choices'][0]['message']['content']
        except Exception as e:
            print(f"API请求错误: {str(e)}")
            return None

    def translate(self, text):
        """将英文文本翻译成中文"""
        messages = [
            {
                "role": "system",
                "content": "你是一个专业的翻译器，请将以下英文文本准确翻译成中文，保持专业性和可读性。"
            },
            {
                "role": "user",
                "content": text
            }
        ]
        return self._make_api_request(messages)

    def summarize(self, text):
        """对文本进行摘要总结"""
        messages = [
            {
                "role": "system",
                "content": "请对以下文本进行简明扼要的总结，突出核心要点，使用中文回答。"
            },
            {
                "role": "user",
                "content": text
            }
        ]
        return self._make_api_request(messages)


    def judge_idea(self, text):
        """对文本进行摘要总结"""
        messages = [
            {
                "role": "system",
                "content": "请对以下文本进行简明扼要的总结，突出核心要点，使用中文回答。"
            },
            {
                "role": "user",
                "content": text
            }
        ]
        return self._make_api_request(messages)

    def extract_shopify_requirements(self, text):
        """从文本中提取潜在的Shopify插件开发需求"""
        messages = [
            {
                "role": "system",
                "content": """你是一个Shopify插件开发专家，请分析以下文本，提取可能的Shopify插件开发需求。
                返回格式要求：
                1. 需求描述
                2. 可行性分析
                3. 技术要点
                4. 开发建议
                请使用中文回答。"""
            },
            {
                "role": "user",
                "content": text
            }
        ]
        return self._make_api_request(messages)

    def process_text(self, text):
        """处理文本的综合方法，返回所有分析结果"""
        results = {
            "original_text": text,
            "translation": self.translate(text),
            "summary": self.summarize(text),
            "shopify_requirements": self.extract_shopify_requirements(text)
        }
        return results
